package com.basics.common.utils.security;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.Random;

public class Md5Utils {
    private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);

    public Md5Utils() {
    }

    private static byte[] md5(String s) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        } catch (Exception var3) {
            log.error("MD5 Error...", var3);
            return null;
        }
    }

    private static final String toHex(byte[] hash) {
        if (hash == null) {
            return null;
        } else {
            StringBuffer buf = new StringBuffer(hash.length * 2);

            for(int i = 0; i < hash.length; ++i) {
                if ((hash[i] & 255) < 16) {
                    buf.append("0");
                }

                buf.append(Long.toString((long)(hash[i] & 255), 16));
            }

            return buf.toString();
        }
    }

    public static String hash(String s) {
        try {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        } catch (Exception var2) {
            log.error("not supported charset...{}", var2);
            return s;
        }
    }

    public static String random(int n) {
        if (n >= 1 && n <= 10) {
            Random ran = new Random();
            if (n == 1) {
                return String.valueOf(ran.nextInt(10));
            } else {
                int bitField = 0;
                char[] chs = new char[n];

                for(int i = 0; i < n; ++i) {
                    int k;
                    do {
                        k = ran.nextInt(10);
                        if (i == 0 && k == 0) {
                            ++k;
                        }
                    } while((bitField & 1 << k) != 0);

                    bitField |= 1 << k;
                    chs[i] = (char)(k + 48);
                }

                return new String(chs);
            }
        } else {
            throw new IllegalArgumentException("cannot random " + n + " bit number");
        }
    }

    public static String getCodeByInt(int n) {
        String code = random(n);
        long num = Long.parseLong(code);
        return n == code.length() && num >= 100000L ? code : getCodeByInt(n);
    }
}

